﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using UwaySoft.EsheetServer.BizLogic;
using UwaySoft.EsheetServer.DataLayer;

namespace Uway.EsheetServer.AutoCheckApp
{
    public class ConfigModel
    {
        public ConfigModel()
        {
            Content = "[u]先生/女士，你好，截止[t]，接收客服单数[c]单，谢谢！";
            Minutes = 60;
            Users = "{用户名|手机号码}";
        }

        public string Users { get; set; }

        public string Content { get; set; }

        public int Minutes { get; set; }

        public string SendMessage()
        {
            try
            {
                var smcHelper = new SmcService.SmcServiceClient();
                var matchs = Regex.Matches(Users, @"\{[\u4e00-\u9fa5]+\|\d*\}");

                if (matchs.Count == 0)
                {
                    return "未配置短信接收用户";
                }

                int count = GetCount();
                var bldr = new StringBuilder();

                foreach (Match match in matchs)
                {
                    var user = match.Value.Replace("{", string.Empty).Replace("}", string.Empty).Split('|');

                    if (user.Length < 2)
                    {
                        continue;
                    }

                    var content = Content.Replace("[u]", user[0]).Replace("[c]", count + "").Replace("[t]", DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"));
                    var result = smcHelper.deliver("1", "c4ca4238a0b923820dcc509a6f75849b", 2, 1, 1, string.Format("<PHONE>{0}</PHONE>", user[1]), 1, content, string.Empty);

                    bldr.AppendFormat("向用户{0}发送短信 {1}！\r\n", user[0], result == 0 ? "成功" : "失败");
                }

                return bldr.ToString();
            }
            catch (Exception ex)
            {
                return string.Format("发生未知错误：{0}", ex.Message);
            }
            
        }

        private int GetCount()
        {
            var commdText = string.Format(
                @"SELECT COUNT(SHEETID)
                  FROM MOD_COMPLAINTS_ITEM T
                 WHERE T.IMPORT_TIME >= TO_DATE('{0}','YYYY-MM-DD HH24:MI:SS')
                   AND T.IMPORT_TIME <= TO_DATE('{1}','YYYY-MM-DD HH24:MI:SS')",
                DateTime.Now.AddMinutes(-Minutes),
                DateTime.Now);

            UwaySoft.EsheetServer.BizLogic.Log.Info("执行命令：" + commdText);

            return Application.SqlHelper.ExecuteScalar<int>(commdText);
        }
    }
}
